﻿using System.Collections.Generic;
using System.Xml;


namespace ArcEngine.Resources
{
	/// <summary>
	/// Helper class that automates text strings management. You may define all your strings in a single text
	/// file and use it to access them by name (makes localization for different countries much easier). 
	/// </summary>
	public class StringTable : ResourceBase
	{

		/// <summary>
		/// Constructeur
		/// </summary>
		/// <param name="name"></param>
		public StringTable(string name) : base(name)
		{
			Strings = new Dictionary<string, string>();
		}


		#region IO routines

		///
		///<summary>
		/// Save the collection to a xml node
		/// </summary>
		///
		public override bool Save(XmlWriter xml)
		{
			if (xml == null)
				return false;

			xml.WriteStartElement("stringtable");
			xml.WriteAttributeString("name", Name);


			base.SaveComment(xml);

			foreach (KeyValuePair<string, string> val in Strings)
			{
				xml.WriteStartElement("string");
				xml.WriteAttributeString("name", val.Key.ToString());
				xml.WriteRaw(val.Value.ToString());
				xml.WriteEndElement();

			}

			xml.WriteEndElement();

			return true;
		}


		/// <summary>
		/// 
		/// </summary>
		/// <param name="xml"></param>
		/// <returns></returns>
		public override bool Load(XmlNode xml)
		{
			// Process datas
			XmlNodeList nodes = xml.ChildNodes;
			foreach (XmlNode node in nodes)
			{
				if (node.NodeType == XmlNodeType.Comment)
				{
					base.LoadComment(node);
					continue;
				}


				switch (node.Name.ToLower())
				{
					// Found a cell to add
					case "string":
					{
						Strings[node.Attributes["name"].Value] = node.InnerText;
					}
					break;


					default:
					{
						Log.Send(new LogEventArgs(LogLevel.Warning, "StringTable : Unknown node element found \"" + node.Name + "\"", null));
					}
					break;
				}
			}

			return true;
		}

		#endregion


		/// <summary>
		/// Returns the value of key
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public string GetString(string key)
		{
			if (Strings.ContainsKey(key))
				return (string )Strings[key];

			return "";
		}


		/// <summary>
		/// Adds a new key - value pair
		/// </summary>
		/// <param name="key"></param>
		/// <param name="value"></param>
		public void Add(string key, string value)
		{
			if (key == null)
				return;

			Strings[key] = value;
		}


		/// <summary>
		/// Returns all strings
		/// </summary>
		/// <returns></returns>
		public string[] GetStrings()
		{
			string[] keys = new string[Strings.Count];
			int id = 0;

			foreach (string st in Strings.Keys)
			{
				keys[id++] = st;
			}
			return keys;
		}

		#region Variables

		/// <summary>
		/// 
		/// </summary>
		//Hashtable Strings;
		Dictionary<string, string> Strings;

		#endregion


	}

}
